#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
调试脚本 - 查看appledb.dev的实际HTML结构
"""

import os
import sys
import requests
from bs4 import BeautifulSoup
from dotenv import load_dotenv

# 设置标准输出编码为UTF-8
if sys.platform == 'win32':
    import io
    sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')

load_dotenv()

device_model = os.getenv('DEVICE_MODEL', 'iPad11,2')
target_version = os.getenv('TARGET_VERSION', '26.0.1')

url = f"https://appledb.dev/device/{device_model}"

print(f"正在访问: {url}")
print(f"目标版本: {target_version}")
print(f"设备型号: {device_model}")
print("=" * 80)

try:
    headers = {
        'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36'
    }
    
    response = requests.get(url, headers=headers, timeout=30)
    response.raise_for_status()
    
    print(f"\n[OK] HTTP状态码: {response.status_code}")
    
    soup = BeautifulSoup(response.text, 'html.parser')
    
    # 保存原始HTML到文件
    with open('debug_page.html', 'w', encoding='utf-8') as f:
        f.write(response.text)
    print(f"[OK] 原始HTML已保存到 debug_page.html")
    
    # 查找所有可能包含版本信息的元素
    print("\n" + "=" * 80)
    print("查找包含版本号的元素:")
    print("=" * 80)
    
    # 方法1: 查找所有包含数字和点的文本
    all_text = soup.get_text()
    lines = [line.strip() for line in all_text.split('\n') if line.strip()]
    
    version_like = []
    for line in lines:
        if '.' in line and any(char.isdigit() for char in line):
            # 检查是否可能是版本号
            parts = line.split()
            for part in parts:
                if '.' in part and any(char.isdigit() for char in part):
                    if part not in version_like:
                        version_like.append(part)
    
    print(f"\n找到 {len(version_like)} 个可能的版本号:")
    for v in version_like[:50]:  # 只显示前50个
        marker = " <-- TARGET" if target_version in v else ""
        print(f"  - {v}{marker}")
    
    # 检查目标版本是否存在
    found = any(target_version in v for v in version_like)
    print(f"\n[{'OK' if found else 'FAIL'}] 目标版本 {target_version} {'找到' if found else '未找到'}")
    
    # 方法2: 查找表格
    print("\n" + "=" * 80)
    print("查找表格结构:")
    print("=" * 80)
    
    tables = soup.find_all('table')
    print(f"找到 {len(tables)} 个表格")
    
    for i, table in enumerate(tables):
        print(f"\n表格 #{i+1}:")
        rows = table.find_all('tr')
        print(f"  行数: {len(rows)}")
        if rows:
            # 显示前3行
            for j, row in enumerate(rows[:3]):
                cells = row.find_all(['td', 'th'])
                cell_text = [cell.get_text(strip=True) for cell in cells]
                print(f"  行{j+1}: {cell_text}")
    
    # 方法3: 查找特定class
    print("\n" + "=" * 80)
    print("查找特定CSS类:")
    print("=" * 80)
    
    interesting_classes = ['version', 'ios', 'firmware', 'signed', 'status']
    for cls in interesting_classes:
        elements = soup.find_all(class_=lambda x: x and cls in str(x).lower())
        if elements:
            print(f"\n包含 '{cls}' 的元素: {len(elements)} 个")
            for elem in elements[:3]:
                print(f"  - {elem.name}: {elem.get('class')} -> {elem.get_text(strip=True)[:100]}")
    
    # 方法4: 查找所有链接
    print("\n" + "=" * 80)
    print("查找iOS版本链接:")
    print("=" * 80)
    
    links = soup.find_all('a', href=True)
    ios_links = [link for link in links if 'ios' in link['href'].lower() or any(char.isdigit() for char in link['href'])]
    
    print(f"找到 {len(ios_links)} 个可能相关的链接")
    for link in ios_links[:20]:
        text = link.get_text(strip=True)
        href = link['href']
        marker = " <-- TARGET" if target_version in text or target_version in href else ""
        print(f"  - {text} -> {href}{marker}")
    
    # 尝试API
    print("\n" + "=" * 80)
    print("尝试API接口:")
    print("=" * 80)
    
    api_url = f"https://api.appledb.dev/device/{device_model}.json"
    print(f"API URL: {api_url}")
    
    try:
        api_response = requests.get(api_url, timeout=15)
        if api_response.status_code == 200:
            data = api_response.json()
            
            with open('debug_api.json', 'w', encoding='utf-8') as f:
                import json
                json.dump(data, f, ensure_ascii=False, indent=2)
            
            print("[OK] API响应已保存到 debug_api.json")
            print(f"\nAPI数据结构:")
            print(f"  Keys: {list(data.keys())}")
            
            # 查找版本信息
            if 'ios' in data:
                print(f"\n  iOS版本数: {len(data['ios'])}")
                for ios in data['ios'][:5]:
                    version = ios.get('version', ios.get('osStr', 'N/A'))
                    signed = ios.get('signed', 'N/A')
                    marker = " <-- TARGET" if target_version in str(version) else ""
                    print(f"    - {version} (signed: {signed}){marker}")
        else:
            print(f"[FAIL] API返回状态码: {api_response.status_code}")
    except Exception as e:
        print(f"[FAIL] API请求失败: {e}")
    
    print("\n" + "=" * 80)
    print("调试完成！请检查:")
    print("  1. debug_page.html - 网页原始HTML")
    print("  2. debug_api.json - API响应数据")
    print("=" * 80)
    
except Exception as e:
    print(f"[ERROR] 错误: {e}")
    import traceback
    traceback.print_exc()

